package offer.of07;

public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return build(preorder,inorder,0,inorder.length-1,0,inorder.length-1);
    }
    public TreeNode build(int[] preorder,int[] inorder,int start1,int end1,int start2,int end2){
        if (start1>end1){
            return null;
        }
        int root=preorder[start1];
        TreeNode node=new TreeNode(root);
        for (int i = start2; i <= end2; i++) {
            if (inorder[i]==root){

                if (start1+1< inorder.length){
                    node.left=build(preorder,inorder,start1+1,start1+(i-start2),start2,i-1);
                }
                if (start1+1+(i-start2)< inorder.length){
                    node.right=build(preorder,inorder,start1+1+(i-start2),end1,i+1,end2);

                }

            }
        }
        return node;
    }
}
class TreeNode{
    TreeNode left;
    TreeNode right;
    int val;
    TreeNode(int x){
        
        val=x;
    }
}